﻿using System;
using System.Linq;
using System.Web.Http;
using ScrambledEggs.Entities;
using ScrambledEggs.Models;

namespace ScrambledEggs.Controllers.Api
{
    public class SavesController : ApiController
    {
        private ScrambledEggsEntities _entities;

        public SavesController()
        {
            // ReSharper disable EmptyGeneralCatchClause
            try
            {
                var conn = System.Configuration.ConfigurationManager.ConnectionStrings["ScrambledEggsConnection"].ConnectionString;
                _entities = new ScrambledEggsEntities(conn);
            }
            catch (Exception)
            {

            }
            // ReSharper restore EmptyGeneralCatchClause
        }

        public String Get(String key)
        {
            var guid = Guid.Parse(key);
            return _entities == null
                ? SaveDictionary.Saves[key]
                : _entities.Saves.Single(save => save.StateKey == guid).State;
        }

        public void Put(SaveModel model)
        {
            var guid = Guid.Parse(model.Key);
            if (_entities != null) {
                var currentSave = _entities.Saves.SingleOrDefault(save => save.StateKey == guid) ?? _entities.Saves.Add(new Save {StateKey = guid});
                currentSave.LastUpdate = DateTime.Now;
                currentSave.State = model.State;
                _entities.SaveChanges();
            }
            SaveDictionary.Saves[model.Key] = model.State;
        }

        public class SaveModel
        {
            public String Key { get; set; }
            public String State { get; set; }
        }
    }
}